from Tkinter import *

from djwindow import *

# An application has exactly one window. To make another window, use DjApplicationSubwindow
class DjApplication():
	def __init__(self):
		windowBaseControl = Tk()
		self._setup(windowBaseControl)
		
	def _setup(self, windowBaseControl):
		self._tkroot = windowBaseControl._root()
		self.window = DjWindow(windowBaseControl)
		self.layout(self.window)
		
		menubar = self.menubar(self.window)
		if menubar:
			self.window.menubar = menubar
	
	#The following are intended to be overridden.
	def layout(self): raise NotImplementedError, 'This method must be overridden'
	def menubar(self, window): return None
	
	# Utility methods
	def run(self):
		"""Run the application. Use .quit() to exit this loop."""
		self._tkroot.mainloop()
		
	def quit(self):
		"""Close the application. (exits the current event loop)"""
		self._tkroot.quit()
	
	def setTimeout(self, n, fn,*args):
		"""Pause for at least n milliseconds, and then call fn."""
		return self._tkroot.after(n, fn,*args)
		
	def cancelTimeout(self, id):
		"""Cancel a timeout created by setTimeout"""
		return self._tkroot.after_cancel(id)

	def beep(self):
		"""Generate a sound (typically a short beep)."""
		return self._tkroot.bell()
	
	def get_clipboard(self):
		"""Returns the contents of the clipboard, as a string. Returns None if the clipboard contents are not a string."""
		try:
			return self._tkroot.clipboard_get()
		except TclError:
			return None
		
	def set_clipboard(self, strText):
		"""Set the contents of the clipboard (with a string)."""
		self._tkroot.clipboard_clear()
		self._tkroot.clipboard_append(strText)
	
	#Events
	
	def _callback_shortcut_keys(self, strKey):
		"""Called when a shortcut key is pressed"""
		if strKey in self._dictShortcutKeys:
			self._dictShortcutKeys[strKey]()
		
	def set_onkey_callback(self, d):
		"""Provide a dictionary mapping keys to callback functions. These bindings are application-wide."""
		from Djoser.tkwrappers import tk_events
		
		if 'Alt+F4' not in d: d['Alt+F4'] = self.quit # By default, add the Alt-F4 to quit
		self._dictShortcutKeys = d
		tk_events.bind_keyevents(self._tkroot, self._callback_shortcut_keys, True)
		
	
	def bind_all(self, *args):
		"""Create binding for entire application."""
		return self._tkroot.bind_all(*args) #and in the darkness bind them.

def _stringToCompoundDict(): return {'no_label':NONE,'center':CENTER,'bottom':BOTTOM,'left':LEFT,'right':RIGHT,'top':TOP}
def _stringToCompound(value): return _stringToCompoundDict()[value] 
def _compoundToString(value): return djcontrolutil.dictInverse(_stringToCompoundDict())[value]
